<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { getDietListApi, getDietByIdApi, addDietApi, updateByIdDietApi, delDietByIdsApi } from '/src/api/diet.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
onMounted(() => {
  getList()
})

const tableData = ref([]);
const searchDishInfo = ref({
  name: '',
  categoryId: '',
  status: '',
  page: 1,
  pageSize: 5
})
//token
const token = ref('123456')
//加载页面
const loading = ref(true)
//一共多少数据
const total = ref(0)
//分页条背景色
const background = ref(true)
//当前页码以及当前页的total
const currentPage = ref(1)
const pageSize = ref(5)
const getList = async () => {
  const result = await getDietListApi(searchDishInfo.value.name, searchDishInfo.value.categoryId, searchDishInfo.value.status, currentPage.value, pageSize.value)
  if (result.code) {
    tableData.value = result.data.rows
    total.value = result.data.total
    loading.value = false
  }
  else {
    tableData.value = []
  }
}
const search = () => {
  if (searchDishInfo.value.name === '' && searchDishInfo.value.categoryId === '' && searchDishInfo.value.status === '') {
    ElMessage.warning('请选择查询条件')
  }
  loading.value = true
  getList()
}
const clear = () => {
  searchDishInfo.value = {
    name: '',
    categoryId: '',
    status: '',
    page: 1,
    pageSize: 5
  }
  ElMessage.success('清空成功')
  loading.value = true
  getList()
}
//操作表格

const handleCurrentChange = () => {
  // 处理当前页变化的逻辑
  getList()
}
const handleSizeChange = () => {
  // 处理分页的总数变化的逻辑
  getList()
}
//编辑弹框显示
const dialogFormVisible = ref(false)
//照片预览显示
const imageDialogVisible = ref(false)
//新增或编辑标题
const title = ref('')
//菜品分类显示下拉框显示
const categoryList = ref([{ name: '早餐', value: 1 }, { name: '午餐', value: 2 }, { name: '晚餐', value: 3 }])
//菜品状态显示下拉框显示
const statusList = ref([{ name: '草稿', value: 0 }, { name: '发布', value: 1 }, { name: '下架', value: 2 }])

//编辑数据回显
const dishData = ref({
  id: '',
  // id不要忘记回过来，修改的时候要用
  name: '',
  categoryId: '',
  status: '',
  imageUrl: '',
  suggest: '',
  step: ''
})

//富文本对象
const quillEditorRef = ref()
const dishFormRef = ref()
//新增菜品
const addDish = () => {
  title.value = '新增菜品'
  dishData.value = {
    id: '',
    name: '',
    categoryId: '',
    status: '',
    imageUrl: '',
    suggest: '',
    step: ''
  }
  //重置富文本框
  // quillEditorRef.value.setHTML('')
  nextTick(() => { quillEditorRef.value.setHTML('') })
  //nextTick是 Vue 的 "等 DOM 更新完再通知我" 机制

  // 表单校验重置
  if (dishFormRef.value) {
    dishFormRef.value.resetFields()
  }

  dialogFormVisible.value = true
}
const handleEdit = async (id) => {
  title.value = '编辑菜品'
  // 表单校验重置
  if (dishFormRef.value) {
    dishFormRef.value.resetFields()
  }
  dialogFormVisible.value = true
  const result = await getDietByIdApi(id)
  dishData.value = result.data
}

//提交数据
const submit = () => {
  //表单校验
  if (!dishFormRef.value) return
  dishFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log(dishData.value);

      let result;
      //表单校验通过
      if (dishData.value.id) {
        //修改员工信息
        result = await updateByIdDietApi(dishData.value)
        if (result.code) {
          ElMessage.success('修改成功')
          dialogFormVisible.value = false
          getList()
        } else {
          ElMessage.error(result.msg)
        }
      }
      else {
        //添加操作
        result = await addDietApi(dishData.value)
        if (result.code) {
          ElMessage.success('添加成功')
          dialogFormVisible.value = false
          getList()
        } else {
          ElMessage.error(result.msg)
        }
      }
    } else {
      ElMessage.error('表单校验不通过！')
    }
  })
}
//获取选择的id数组
const selectIds = ref([])
//1，批量选择操作
const handleSelectionChange = (val) => {
  // console.log(val);
  //获取的是一个代理对象数组，里面有每个对象的id
  selectIds.value = val.map(item => {
    return item.id
  })
  console.log(selectIds.value);
}
//批量删除菜品数据
const delDishes = () => {
  ElMessageBox.confirm(
    '你确定要删除这些吗',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (selectIds.value && selectIds.value.length > 0) {
        const result = await delDietByIdsApi(selectIds.value)
        if (result.code) {
          getList()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        } else {
          ElMessage.error(result.msg)
        }
      } else {
        ElMessage({
          type: 'error',
          message: '请勾选数据',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//删除菜品数据
const handleDelete = (id) => {
  ElMessageBox.confirm(
    '你确定要删除吗',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await delDietByIdsApi(id)
      if (result.code) {
        getList()
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//新增表单校验
const rules = ref({
  name: [
    { required: true, message: '菜品名称不能为空', trigger: 'blur' },
    { min: 2, message: '长度要大于1位', trigger: 'blur' },
  ],
  step: [
    { required: true, message: '菜品步骤不能为空', trigger: 'blur' },
    {
      min: 6,
      message: '长度要大于6位',
      trigger: 'blur',
    }
  ],
})

// 富文本校验  ?????????????  TODO
// const contentRule = () => {
//   quillEditorRef.value.addModelRef.validateField('step')
// }

//预览照片
const previewImage = ref('')
const handlePreview = (url) => {
  previewImage.value = url
  imageDialogVisible.value = true
}
//上传照片
const uploadImageSuccess = (response) => {
  dishData.value.imageUrl = response.data
}

const beforeImageUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}

</script>
<template>
  <PageContainer title="饮食管理">
    <!-- 头部--表单 -->
    <div class="container">

      <el-form :inline="true" :model="searchDishInfo" class="demo-form-inline">
        <el-form-item label="菜品名称">
          <el-input v-model="searchDishInfo.name" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品分类">
          <el-select v-model="searchDishInfo.categoryId" placeholder="请选择菜品分类">
            <el-option label="早餐" value="1" />
            <el-option label="午餐" value="2" />
            <el-option label="晚餐" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品状态">
          <el-select v-model="searchDishInfo.status" placeholder="请选择菜品状态">
            <el-option label="草稿" value="0" />
            <el-option label="发布" value="1" />
            <el-option label="下架" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增、批量删除按钮-->
    <div class="container">
      <el-button type="primary" @click="addDish">+ 新增菜品</el-button>
      <el-button type="info" @click="delDishes">- 批量删除</el-button>
    </div>
    <!-- 表格 -->
    <div class="container">
      <el-table :data="tableData" style="width: 100%" border v-loading="loading" element-loading-text="加载中..."
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="46" align="center" />
        <el-table-column label="id" width="56" type="index" align="center">
        </el-table-column>
        <el-table-column label="菜品名称" width="120" prop="name" align="center">
        </el-table-column>
        <el-table-column label="菜品图片" width="120" prop="imageUrl" align="center">
          <template #default="scope">
            <img :src="scope.row.imageUrl" width="66px" style="cursor: pointer; object-fit: cover; border-radius: 4px;"
              @click="handlePreview(scope.row.imageUrl)">
          </template>
        </el-table-column>

        <el-table-column label="菜品步骤" width="175" prop="step" align="center">
          <!-- 从富文本中回显过来 -->
          <template #default="scope">
            <div v-html="scope.row.step"></div>
          </template>
        </el-table-column>
        <el-table-column label="建议" width="110" prop="suggest" align="center">
        </el-table-column>
        <el-table-column label="分类" width="75" prop="categoryId" align="center">
          <template #default="scope">
            <span v-if="scope.row.categoryId === 1">早餐</span>
            <span v-else-if="scope.row.categoryId === 2">午餐</span>
            <span v-else>晚餐</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="75" prop="status" align="center">
          <template #default="scope">
            <span v-if="scope.row.status === 0">草稿</span>
            <span v-else-if="scope.row.status === 1">发布</span>
            <span v-else>下架</span>
          </template>
        </el-table-column>
        <el-table-column label="浏览次数" width="81" prop="viewCount" align="center">
        </el-table-column>
        <el-table-column label="点赞次数" width="81" prop="praiseCount" align="center">
        </el-table-column>
        <el-table-column label="收藏次数" width="81" prop="collectCount" align="center">
        </el-table-column>
        <el-table-column label="创建时间" width="97" prop="createTime" align="center">
        </el-table-column>
        <el-table-column label="更新时间" width="97" prop="updateTime" align="center">
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template #default="scope">
            <el-button type="primary" plain @click="handleEdit(scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" plain @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
        :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        style="margin-top: 20px;justify-content: start;" />
      <!-- 预览照片弹框 -->
      <el-dialog title="照片预览" v-model="imageDialogVisible" width="50%" top="5vh">
        <img :src="previewImage">
      </el-dialog>
    </div>

    <!-- 编辑/新增菜品弹框 -->
    <div class=" container">
      <el-dialog v-model="dialogFormVisible" :title="title" width="700" top="4vh">
        <el-form :model="dishData" :rules="rules" ref="dishFormRef">
          <el-form-item label="菜品名称" :label-width="100" prop="name">
            <el-input v-model="dishData.name" autocomplete="off" placeholder="请输入菜品名称" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="菜品分类" :label-width="100">
            <el-select v-model="dishData.categoryId" placeholder="请选择" style="width: 250px;">
              <el-option v-for="category in categoryList" :label="category.name" :value="category.value"
                :key="category.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="菜品状态" :label-width="100">
            <el-select v-model="dishData.status" placeholder="请选择" style="width: 250px;">
              <el-option v-for="status in statusList" :label="status.name" :value="status.value" :key="status.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="菜品封面" :label-width="100" style="width: 100%;">
            <el-upload class="avatar-uploader" name="file" :show-file-list="false" :auto-upload="true"
              :headers="{ 'token': token }" :on-success="uploadImageSuccess" action="/api/diets/upload"
              :before-upload="beforeImageUpload">
              <img v-if="dishData.imageUrl" :src="dishData.imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <!--   :headers="{ 'token': token }"  -->
          <el-form-item label="菜品建议" :label-width="100" style="width: 75%;">
            <el-input type="textarea" v-model="dishData.suggest" placeholder="请输入对菜品的建议"></el-input>
          </el-form-item>
          <el-form-item label="菜品步骤" :label-width="100" style="width: 75%;" prop="step">
            <div class="editor">
              <quill-editor ref="quillEditorRef" theme="snow" v-model:content="dishData.step" @blur="contentRule"
                contentType="html">
              </quill-editor>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submit">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </PageContainer>
</template>

<style lang="scss" scoped>
.container {
  margin: 10px 0;

  .avatar-uploader {
    :deep() {
      .avatar {
        width: 165px;
        height: 165px;
        display: block;
      }

      .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }

      .el-upload:hover {
        border-color: var(--el-color-primary);
      }

      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 165px;
        height: 165px;
        text-align: center;
      }
    }
  }

  .editor {
    width: 100%;

    :deep(.ql-editor) {
      min-height: 200px;
    }
  }
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>